#coding:utf8
from django.conf import settings
from urllib.parse import urlencode,parse_qs
from urllib.request import urlopen
import json

class QQOauth(object):

    def get_oauth_url(self):
        # 确定请求的url
        base_url = 'https://graph.qq.com/oauth2.0/authorize?'

        state = '/'

        # 确定请求的参数
        params = {
            'response_type': 'code',
            'client_id': settings.QQ_APP_ID,
            'redirect_uri': settings.QQ_REDIRECT_URL,
            'state': state
            # 'scope':'get_user_info'
        }
        # 将参数拼接到url中
        # 我们需要对字典进行 key=value&key=value 的操作
        #
        # from urllib.parse import urlencode
        # urlencode 就可以将字典转换为 key=value&key=value 的形式
        auth_url = base_url + urlencode(params)

        return auth_url


    def get_access_token(self,code):
        # 1. 确定base_url
        base_url = 'https://graph.qq.com/oauth2.0/token?'
        # 2. 拼接参数
        params = {
            'grant_type': 'authorization_code',
            'client_id': settings.QQ_APP_ID,
            'client_secret': settings.QQ_APP_KEY,
            'code': code,
            'redirect_uri': settings.QQ_REDIRECT_URL
        }
        # 3. 生成url
        token_url = base_url + urlencode(params)

        # 4. 发送请求,获取返回数据
        # from urllib.request import urlopen
        # 发送请求
        response = urlopen(token_url)

        # respones 可以通过 read来读取,但是它 bytes类型
        data = response.read().decode()

        from urllib.parse import parse_qs
        # 将qs查询字符串格式数据转换为python的字典
        res_params = parse_qs(data)

        # print(res_params)
        access_token = res_params['access_token']

        # print(access_token)
        # <class 'list'>: ['7D74280305974000D2C83ACCDAD52986']

        access_token = access_token[0]

        return access_token


    def get_openid(self,access_token):

        # https://graph.qq.com/oauth2.0/me
        # GET
        # access_token        必须      在Step1中获取到的accesstoken。

        # 返回数据PC网站接入时，获取到用户OpenID，返回包如下：
        # callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} );
        # openid是此网站上唯一对应用户身份的标识，网站可将此ID进行存储便于用户下次登录时辨识其身份，
        # 或将其与用户在网站上的原有账号进行绑定

        base_url = 'https://graph.qq.com/oauth2.0/me?'

        params = {
            'access_token':access_token
        }

        openidurl = base_url + urlencode(params)

        # 请求url的数据
        response = urlopen(openidurl)
        # 获取url的数据
        data = response.read().decode()

        print(data)
        #'callback( {"client_id":"101474184","openid":"6347C1A6384797C43AD70F277A500A57"} );'
        try:
            dict = json.loads(data[10:-4])
        except Exception:
            raise Exception('数据读取错误')

        print(dict)
        #{'openid': '63850E40C3AB65589E8E9025E2069953', 'client_id': '101474184'}

        return dict.get('openid',None)


